package com.fangwaii.core.socket.handlers;

import com.fangwaii.core.bind.IGenericReference;
import com.fangwaii.core.session.GatewaySession;
import com.fangwaii.core.session.defaults.DefaultGatewaySessionFactory;
import com.fangwaii.core.socket.BaseHandler;
import com.fangwaii.core.socket.agreement.ResponseParser;
import com.fangwaii.core.socket.agreement.AgreementConstants;
import com.fangwaii.core.socket.agreement.GatewayResult;
import com.fangwaii.core.socket.agreement.RequestParser;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

import static io.netty.resolver.HostsFileParser.parse;

/**
 * @author lxc18
 * @date 2024/11/29 11:23
 * @description SessionServerHandler
 */
public class GatewayServerHandler extends BaseHandler<FullHttpRequest> {
    private final Logger logger = LoggerFactory.getLogger(GatewayServerHandler.class);
    private final DefaultGatewaySessionFactory gatewaySessionFactory;

    public GatewayServerHandler(DefaultGatewaySessionFactory gatewaySessionFactory) {
        this.gatewaySessionFactory = gatewaySessionFactory;

    }

    @Override
    protected void session(ChannelHandlerContext channelHandlerContext, Channel channel, FullHttpRequest request) {
        //处理业务逻辑的地方


        logger.info("网关接收请求 uri：{} method：{}", request.uri(), request.method());
        try {
            RequestParser requestParser = new RequestParser(request);
            //对uri的内容进行解析
            Map<String, Object> parse = requestParser.parse();

            // 返回信息控制：简单处理
            String uri = requestParser.getUri();

            GatewaySession gatewaySession = gatewaySessionFactory.openSession(uri);
            IGenericReference reference = gatewaySession.getMapper();
            //统一的调用接口，传入的参数是Map<String, Object> parse
            Object result = reference.$invoke(parse);

            // 3. 封装返回结果
            GatewayResult gatewayResult = GatewayResult.gatewaySucess(result);
            DefaultFullHttpResponse response = new ResponseParser().parse(gatewayResult);


            channel.writeAndFlush(response);
        } catch (Exception e) {
            DefaultFullHttpResponse response = new ResponseParser().parse(
                    GatewayResult.gatewayFail(AgreementConstants.ResponseCode._500.getCode(), "网关协议调用失败！" + e.getMessage()));
            channel.writeAndFlush(response);
        }


    }
}
